public class Sort2 {

    /*
    堆排序
    时间复杂度 : O(N*logN)
    空间复杂度 : O(1)
    稳定性  : 不稳定

    */

    public static void heapSort(int[] array) {
        //创建一个大根堆
        createHeap(array);
        int end = array.length -1;
        while (end > 0) {
            swap(array,0,end);
            siftDown(array,0,end);
            end--;
        }
    }

    public static void createHeap(int[] array) {
        for (int parent = (array.length-1-1)/2;parent >= 0; parent--) {
            siftDown(array,parent,array.length);
        }
    }

    public static void siftDown(int[] array,int parent,int len) {
        int child = (2 * parent) +1;
        while (child < len) {
            if (child + 1 < len && array[child] < array[child+1]) {
                child = child+1;
            }
            if (array[child] > array[parent]) {
                swap(array,child,parent);
                parent = child;
                child = 2*child+1;
            }else {
                break;
            }
        }
    }

    public static void swap(int[] array,int child,int parent) {
        int tmp = array[parent];
        array[parent] = array[child];
        array[child] = tmp;
    }
    public static void main(String[] args) {
        int[] arr = {1,3,2,8,5,7,3};
        heapSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
